package com.elong.qadev.run;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;

import com.elong.qadev.compiler.DynamicEngine;
import com.elong.qadev.entity.WebuiCase;
import com.elong.qadev.selenium.DriverFactory;
import com.elong.qadev.selenium.EventListener;
import com.elong.qadev.tools.LogTools;
import com.elong.qadev.uiModel.UiResult;

public class RunWebui {
	Logger logger = Logger.getLogger(RunWebui.class);
	private boolean isExpected;
	public boolean isExpected() {
		return isExpected;
	}
	public void setExpected(boolean isExpected) {
		this.isExpected = isExpected;
	}
	/**
	 * @throws Exception 
	 * 
	* @Title: runReturnResult
	* @Description: TODO(运行执行webui用例)
	* @param @param wc
	* @param @param msg
	* @param @param driverStr
	* @param @return    参数
	* @return String    返回类型
	* @throws
	 */
	public String runReturnResult(WebuiCase wc, String msg,
			String driverStr) throws Exception {

		String codeRun = wc.getCodeContent();
		logger.debug("动态编译代码为：" + codeRun);
		DynamicEngine de = DynamicEngine.getInstance();
		String regex = "class (.*) implements";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(codeRun);
		String className = "";
		if (matcher.find()) {
			className = matcher.group(1);
		}
		logger.debug("获取到的类名称是：" + className);
		UiResult ur = new UiResult();
		try {
			Class<?> oWebui = de.javaCodeToClass(className.trim(), codeRun);
			Object objectWebui = oWebui.newInstance();

			// Thread tempT = new Thread((Runnable) objectWebui);
			// tempT.run();//如果多个用例一起执行，需要使用start方法，同时启动执行
			WebDriver driver = null;
			String[] dv = driverStr.split("-");
			switch (dv[2]) {
			case "WINDOWS":
				driver = DriverFactory.getRemoteWebDriver(dv[0], dv[1],
						Platform.WINDOWS);
				break;
			case "MAC":
				driver = DriverFactory.getRemoteWebDriver(dv[0], dv[1],
						Platform.MAC);
				break;
			case "WIN8":
				driver = DriverFactory.getRemoteWebDriver(dv[0], dv[1],
						Platform.WIN8);
				break;
			case "WIN8_1":
				driver = DriverFactory.getRemoteWebDriver(dv[0], dv[1],
						Platform.WIN8_1);
				break;
			default:
				driver = DriverFactory.getRemoteWebDriver("chrome", "40",
						Platform.WIN8_1);
				break;
			}
			
			EventFiringWebDriver eDriver = new EventFiringWebDriver(driver);
			EventListener el = new EventListener();
			eDriver.register(el);
			eDriver.manage().timeouts().pageLoadTimeout(30L, TimeUnit.SECONDS);
			eDriver.manage().timeouts().implicitlyWait(30L, TimeUnit.SECONDS);
			eDriver.manage().timeouts().setScriptTimeout(30L, TimeUnit.SECONDS);
			
			Method method_run = null;
			Method method_getUr = null;
			Method method_setDriver = null;
			method_setDriver = objectWebui.getClass().getMethod("setDriver",
					EventFiringWebDriver.class);
			method_run = objectWebui.getClass().getMethod("run");				
			method_getUr = objectWebui.getClass().getMethod("getUr");
			method_setDriver.invoke(objectWebui, eDriver);
			Date startDate = null;
			Date endDate = null;
			try{
				startDate=new Date();
				logger.debug("开始执行调用RUN方法："+startDate.toString());
				method_run.invoke(objectWebui);
				endDate = new Date();
				logger.debug("结束执行调用RUN方法："+endDate.toString());
			}catch(Exception e){
				endDate=new Date();
				throw e;
			}
			ur = (UiResult) method_getUr.invoke(objectWebui);
			ur.durations=endDate.getTime()-startDate.getTime();
			logger.debug("持续时间是："+ur.durations);
			logger.debug("执行完毕获取执行结果是：" + ur.toString());
		} catch (Exception e1) {
			ur.setExpected(false);
			this.setExpected(false);
			ur.setErrorMsg(e1.toString());
			throw e1;
		} finally {
			String stepStr = "";
			for (String str : ur.getStepLog()) {
				stepStr += LogTools.log(str);
			}
			msg = ur.isExpected() ? ("状态:运行成功\n持续时间: "+ur.durations/1000.0+" s\n" + stepStr) : ("状态:运行【失败!】\n持续时间: "+ur.durations/1000.0+" s\n" 
					+ stepStr + (ur.getErrorMsg() == null ? "" : ur
					.getErrorMsg()));
			this.setExpected(ur.isExpected());
		}

		return msg;
	}
	
	/**
	 * @throws Exception 
	 * 
	* @Title: runReturnResultByTask
	* @Description: TODO(用线程的方法运行用例)
	* @param @param wc
	* @param @param msg
	* @param @param driverStr
	* @param @return    参数
	* @return String    返回类型
	* @throws
	 */
	public String runReturnResultByTask(WebuiCase wc, String msg,
			String driverStr) throws Exception {

		String codeRun = wc.getCodeContent();
		logger.debug("动态编译代码为：" + codeRun);
		DynamicEngine de = DynamicEngine.getInstance();
		String regex = "class (.*) implements";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(codeRun);
		String className = "";
		if (matcher.find()) {
			className = matcher.group(1);
		}
		logger.debug("获取到的类名称是：" + className);
		UiResult ur = new UiResult();
		try {
			Class<?> oWebui = de.javaCodeToClass(className.trim(), codeRun);
			Object objectWebui = oWebui.newInstance();

			// Thread tempT = new Thread((Runnable) objectWebui);
			// tempT.run();//如果多个用例一起执行，需要使用start方法，同时启动执行
			WebDriver driver = null;
			String[] dv = driverStr.split("-");
			switch (dv[2]) {
			case "WINDOWS":
				driver = DriverFactory.getRemoteWebDriver(dv[0], dv[1],
						Platform.WINDOWS);
				break;
			case "MAC":
				driver = DriverFactory.getRemoteWebDriver(dv[0], dv[1],
						Platform.MAC);
				break;
			case "WIN8":
				driver = DriverFactory.getRemoteWebDriver(dv[0], dv[1],
						Platform.WIN8);
				break;
			case "WIN8_1":
				driver = DriverFactory.getRemoteWebDriver(dv[0], dv[1],
						Platform.WIN8_1);
				break;
			default:
				driver = DriverFactory.getRemoteWebDriver("chrome", "40",
						Platform.WIN8_1);
				break;
			}
			
			EventFiringWebDriver eDriver = new EventFiringWebDriver(driver);
			EventListener el = new EventListener();
			eDriver.register(el);
			
//			Method method_run = null;
			Method method_getUr = null;
			Method method_setDriver = null;
			method_setDriver = objectWebui.getClass().getMethod("setDriver",
					WebDriver.class);
//			method_run = objectWebui.getClass().getMethod("run");				
			method_getUr = objectWebui.getClass().getMethod("getUr");
			method_setDriver.invoke(objectWebui, eDriver);
			Date startDate = null;
			Date endDate = null;
			try{
				startDate=new Date();
				logger.debug("开始执行调用RUN方法："+startDate.toString());
//				method_run.invoke(objectWebui);
				Thread t = new Thread((Runnable) objectWebui);
				t.start();
				while(t.isAlive()){
					endDate = new Date();
					Thread.sleep(10);//误差0.001s
				}
				logger.debug("结束执行调用RUN方法："+endDate.toString());
			}catch(Exception e){
				endDate=new Date();
				throw e;
			}
			ur = (UiResult) method_getUr.invoke(objectWebui);
			ur.durations=endDate.getTime()-startDate.getTime();
			logger.debug("持续时间是："+ur.durations);
			logger.debug("执行完毕获取执行结果是：" + ur.toString());
		} catch (Exception e1) {
			ur.setExpected(false);
			this.setExpected(false);
			ur.setErrorMsg(e1.toString());
			throw e1;
		} finally {
			String stepStr = "";
			for (String str : ur.getStepLog()) {
				stepStr += LogTools.log(str);
			}
			msg = ur.isExpected() ? ("状态:运行成功\n持续时间: "+ur.durations/1000.0+" s\n" + stepStr) : ("状态:运行【失败!】\n持续时间: "+ur.durations/1000.0+" s\n" 
					+ stepStr + (ur.getErrorMsg() == null ? "" : ur
					.getErrorMsg()));
			this.setExpected(ur.isExpected());
		}

		return msg;
	}
	
}
